package com.coocaa.x.app.hall.topic;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.hall.HallBaseActivity;
import com.coocaa.x.app.hall.R;
import com.coocaa.x.app.hall.parser.ActionParser;
import com.coocaa.x.app.hall.parser.ParserData;
import com.coocaa.x.app.hall.view.widget.CircleProgressView;
import com.coocaa.x.app.hall.view.widget.CircleProgressViewFactory;
import com.coocaa.x.app.hall.view.widget.TipToast;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_Content;
import com.coocaa.x.test.action.FocusAction;
import com.coocaa.x.uipackage.BaseView;
import com.coocaa.x.uipackage.widget.CoocaaDraweeView;
import com.coocaa.x.uipackage.widget.SlideFocusView;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by sunny on 15-6-19.
 */
public class TopicLayout extends RelativeLayout implements CircleProgressViewFactory.
        CircleProgressViewFactoryListener, View.OnFocusChangeListener {

    Context mcontext;
    SlideFocusView slide;
    HorizontalScrollView hsv;
    private HSVAdapter adapter = null;
    private ImageView leftArrow;
    private ImageView rightArrow;

    final int preCount = 6;
    final int maxCount = 12;
    int countSize;

    private int shotsWidth = CoocaaApplication.Div(240);
    private int shotsHeight = CoocaaApplication.Div(330);
    private int spacing = CoocaaApplication.Div(30);//CoocaaApplication.Div(-6);
    HSVLayout hsvLayout;

    String bgUri;
    List<String> jsonList;
    List<String> actionJsonList;
    protected HashMap<Integer, String> appItemNumMap = null;
    protected HashMap<String, List<View>> appItemViewMap = null;
    protected Map<Integer, Intent> pkgIntentMap = null;
    private Map<Object, View> updateViewMap = new ConcurrentHashMap<Object, View>();
    private HashSet<Integer> viewIdSet = new HashSet<Integer>();

    static final int REFRESH_LAYOUT = 100;
    static final int REFRESH_FOCUS = 101;
    static final int REFRESH_DOWNLOAD = 102;
    static final int REFRESH_DOWNLOAD_PROGRESS = 103;
    static final int REFRESH_ITEM_CLICKABLE = 104;
    CoocaaDraweeView mSimpleDraweeView;

    private boolean isOneKeySetup = false;
    private Button oneKeySetupBtn;
    private int keyUpItemIndex = 0;
    private String topicId;
    private List<TopicAppInfo> appInfoList = new ArrayList<TopicAppInfo>();

    class TopicAppInfo {
        public String id;
        public String name;
        public String lmg;
        public String downloads;
        public String softwaresize;
        public String packagename;
        public String version;
    }

    Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            // TODO Auto-generated method stub
            super.dispatchMessage(msg);
            switch (msg.what) {
                case REFRESH_LAYOUT:
                    if(isOneKeySetup) {
                        oneKeySetupBtn.setVisibility(VISIBLE);
                    }
                    adapter = new HSVAdapter(mcontext, jsonList);
                    hsvLayout.setmOnClickListener(listener);
                    hsvLayout.setAdapter(adapter);
                    FocusAction action = new FocusAction(adapter.getCount(), 0);
                    hsvLayout.setContentDescription(action.toJSONString());
                    countSize = jsonList.size();
                    if (countSize <= preCount) {
                        rightArrow.setVisibility(View.INVISIBLE);
                    } else {
                        rightArrow.setVisibility(View.VISIBLE);
                    }
                    getAllItemPakageName();
                    LogUtils.i("1103", "bgUri: " + bgUri);
                    mSimpleDraweeView.setImageURI(Uri.parse(bgUri));
                    mHandler.sendEmptyMessage(REFRESH_FOCUS);
                    break;
                case REFRESH_FOCUS:
                    if(!isOneKeySetup)
                        hsvLayout.getChildAt(0).requestFocus();
                    else
                        oneKeySetupBtn.requestFocus();
                    slide.showFocusView();
                    break;
                case REFRESH_DOWNLOAD:
                    checkCircleProgressView(appItemNumMap);
                    break;
                case REFRESH_ITEM_CLICKABLE:
                    String name = msg.getData().getString("pkgName");
                    int itemId = msg.getData().getInt("itemId");
                    View view = hsvLayout.getChildAt(itemId);

                    if (view != null) {
                        view.setClickable(true);
                    }
                    if (name != null && pkgIntentMap.containsKey(name)) {
                        try {
                            HallBaseActivity.logStartApp(name);
//                            mcontext.startActivity(pkgIntentMap.get(itemId));
                            HashMap<String,String> map = new HashMap<String,String>();
                            SkyStartActivity.startActivity(mcontext, mcontext.getClass().getName(), pkgIntentMap.get(itemId), map, false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        pkgIntentMap.remove(itemId);
                    }

                    break;
                case REFRESH_DOWNLOAD_PROGRESS:
                    String pkgName = msg.getData().getString("pkgName");
                    int viewId = msg.getData().getInt("itemId");
                    View v = hsvLayout.getChildAt(viewId);

                    CircleProgressView circleProgressView = (CircleProgressView) msg.obj;
                    if (circleProgressView != null && v != null) {
                        int i = 0;
                        CircleProgressView cirView;
                        cirView = circleProgressView;
                        if (cirView.getParent() != null)
                            break;
                        cirView.setBackgroundResource(R.drawable.downloading_bg);
                        cirView.setTextColor(Color.WHITE);
                        cirView.setBackColor(0x55a4aab0);
                        cirView.setPreColor(0xff01b3fd);
                        cirView.setTextSize(CoocaaApplication.Dpi(40));
                        cirView.setBgWidth(CoocaaApplication.Div(7));
                        cirView.setArcWidth(CoocaaApplication.Div(7));
                        cirView.setRadius((CoocaaApplication.Div(45)));

                        cirView.setWaitText(mcontext.getString(R.string.down_wait_text));
                        cirView.setInstallText(mcontext.getString(R.string.down_install_text));
                        cirView.setUpgradeText(mcontext.getString(R.string.update_text));

                        LinearLayout.LayoutParams itemParams = (LinearLayout.LayoutParams) v.getLayoutParams();
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(itemParams.width + 1, itemParams.height + 1);

                        ((BaseView) v).addView(cirView, params);
                        updateViewMap.put(cirView, v);
                        v.setClickable(false);
                    }
                    break;
                default:
                    break;

            }
        }
    };

    public TopicLayout(Context context) {
        super(context);
        mcontext = context;
        addBgView();
        hsv = new HorizontalScrollView(mcontext);
        hsvLayout = new HSVLayout(mcontext);

        leftArrow = new ImageView(mcontext);
        rightArrow = new ImageView(mcontext);
        leftArrow.setBackgroundResource(R.drawable.left_arrow);
        rightArrow.setBackgroundResource(R.drawable.right_arrow);

        LayoutParams hsvParams = new LayoutParams(CoocaaApplication.Div(1590), shotsHeight);
        hsvParams.leftMargin = CoocaaApplication.Div(155);
        hsvParams.topMargin = CoocaaApplication.Div(673);

        LayoutParams leftParams = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        leftParams.leftMargin = CoocaaApplication.Div(64);
        leftParams.topMargin = CoocaaApplication.Div(818);

        LayoutParams rightParams = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        rightParams.leftMargin = CoocaaApplication.Div(1803);
        rightParams.topMargin = CoocaaApplication.Div(818);
        addView(leftArrow, leftParams);
        addView(rightArrow, rightParams);
        leftArrow.setVisibility(View.INVISIBLE);
        rightArrow.setVisibility(View.INVISIBLE);
        hsv.setHorizontalScrollBarEnabled(false);
        hsv.addView(hsvLayout);
        slide = new SlideFocusView(mcontext, R.drawable.tag_focus);
        hsvLayout.setmFocusChangedEvent(slide.focusChangedEvent);
        hsvLayout.setmonFocusChange(this);
        hsvLayout.setmOnKeyListener(monKeyListener);
        addView(hsv, hsvParams);
        addView(slide);
        slide.hideFocusView();
        appItemNumMap = new HashMap<Integer, String>();
        appItemViewMap = new HashMap<String, List<View>>();
        pkgIntentMap = new HashMap<Integer, Intent>();
        actionJsonList = new ArrayList<String>();

        //add one key setup button
        addOneKeySetupBtn();
        CircleProgressViewFactory.addListener(this);
    }

    public void addOneKeySetupBtn() {
        LayoutParams oneKeySetupParams =  new LayoutParams( CoocaaApplication.Div(320), CoocaaApplication.Div(125));
        oneKeySetupParams.topMargin = CoocaaApplication.Div(330);
        oneKeySetupParams.leftMargin = CoocaaApplication.Div(1497);
        oneKeySetupBtn = new Button(mcontext);
        oneKeySetupBtn.setTextColor(getResources().getColor(R.color.titleColor));
        oneKeySetupBtn.setText("一键安装");
        oneKeySetupBtn.setTextSize(CoocaaApplication.Dpi(40));
        oneKeySetupBtn.setBackgroundResource(R.drawable.onkeysetupbg);
        oneKeySetupBtn.setClickable(false);
        this.addView(oneKeySetupBtn, oneKeySetupParams);
        oneKeySetupBtn.setOnKeyListener(buttonKeyListener);
        oneKeySetupBtn.setOnClickListener(buttonOnKeyListener);
        oneKeySetupBtn.setVisibility(INVISIBLE);

        SlideFocusView.FocusViewRevision mFocusViewRevision = new SlideFocusView.FocusViewRevision(CoocaaApplication.Div(110), CoocaaApplication.Div(110));
        slide.focusChangedEvent.registerView(oneKeySetupBtn, mFocusViewRevision, buttonFocusChangeListener);
    }

    private OnClickListener buttonOnKeyListener = new OnClickListener() {
        @Override
        public void onClick (View view){
            LogUtils.i("topic", "buttonOnKeyListener");
            Intent i  = new Intent("coocaa.intent.action.OneKeySetup.Receiver");
            ArrayList<String> list = new ArrayList<String>();
            if(appInfoList.size() == 0)
                getAppInfoList();

            if(appInfoList.size() == 0)
                return;

            for(TopicAppInfo appInfo: appInfoList) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(appInfo.id).append("|")
                        .append(appInfo.packagename).append("|")
                        .append(appInfo.lmg).append("|")
                        .append(appInfo.name);
                list.add(stringBuilder.toString());
//                list.add(""+appInfo.id+"|"+appInfo.packagename+"|"+appInfo.lmg+"|"+appInfo.name);
            }

            //唤起被强制kill掉应用
            i.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            i.putExtra("topicId", topicId);
            i.putStringArrayListExtra("infolist", list);
            mcontext.sendBroadcast(i);
        }
    };

    private OnFocusChangeListener buttonFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {

        }
    };

    private OnKeyListener buttonKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT
                    || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                return true;
            }

            if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
                hsvLayout.setChildItemFocusByIndex(keyUpItemIndex);
            }
            return false;
        }
    };

    private void addBgView() {
        mSimpleDraweeView = new CoocaaDraweeView(mcontext);
        mSimpleDraweeView
                .getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP);
        mSimpleDraweeView
                .getHierarchy().setPlaceholderImage(R.drawable.bg);

        RoundingParams roundingParams = RoundingParams.fromCornersRadius(1f);
        mSimpleDraweeView.getHierarchy().setRoundingParams(roundingParams);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(SkySystemUtil.getDisplayWidth(mcontext)),
                CoocaaApplication.Div(SkySystemUtil.getDisplayHeight(mcontext)));
//        LogUtils.i("","sunny width:" + CoocaaApplication.Div(SkySystemUtil.getDisplayWidth(mcontext)) + "; " + CoocaaApplication.Div(SkySystemUtil.getDisplayHeight(mcontext)));
        addView(mSimpleDraweeView, params);
    }

    public void refreshLayout(String tid) {
        this.topicId = tid;
        getTopicData(topicId);
    }

    private void getTopicData(final String tid) {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                jsonList = new ArrayList<String>();
                LiteURI uri = LiteURI.create("store://com.coocaa.hall/zonepage");
                uri.addParams("id", tid);
                String json;
                try {
                    json = LiteContentServiceConnecter.getService().call(uri.toString());

                    LogUtils.i("1103", "web json: "+json);
                    RP_Content rp = RP_Content.parseJObject(json, RP_Content.class);
                    if (rp == null) {
                        showTips("数据接收异常");
                        return;
                    }

                    jsonList = rp.resource.resource_items;
                    bgUri = rp.head.bg_url;
                    isOneKeySetup = rp.head.isOneKeySetup;
                    LogUtils.i("topic", ", isOneKeySetup: "+isOneKeySetup);
                    for (String rps : jsonList)
                        LogUtils.i("topic", "json rps:" + rps.toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (jsonList.size() > 0) {
                    if (jsonList.size() > maxCount) {
                        jsonList = jsonList.subList(0, 12);
                    }
                    mHandler.sendEmptyMessage(REFRESH_LAYOUT);
                } else {
                    showTips("数据接收异常");
                    return;
                }


            }

        });

    }

    private void showTips(String str) {
        HallBaseActivity baseActivity = (HallBaseActivity) mcontext;
        baseActivity.showTips(str);
    }

    private boolean networkStatusOK(Context mContext) {
        boolean netStatus = false;
        try {
            ConnectivityManager connectManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null) {
                if (activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected()) {
                    netStatus = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return netStatus;
    }

    private String getPakageName(String actionJson) {
        String pkgName = null;
        ActionParser.ParseIntent intent;
        try {
            ActionParser parser = new ActionParser();
            intent = parser.parse(actionJson);
            if(intent != null)
                pkgName = intent.pkgName;
        } catch (PackageManager.NameNotFoundException e) {
            pkgName = e.getMessage();
            e.printStackTrace();
        }

        return pkgName;
    }

    private void getAllItemPakageName() {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                if (jsonList == null || jsonList.size() <= 0)
                    return;
                for (String json : jsonList) {
                    ParserData.Root_Node action = ParserData.Layout_Node.parseJObject(json, ParserData.Root_Node.class);
                    actionJsonList.add(action.action);
                }
                if (actionJsonList != null && actionJsonList.size() > 0) {
                    String pagName = null;
                    int i = 0;
                    for (String action : actionJsonList) {
                        pagName = getPakageName(action);
                        if (pagName != null) {
                            View view = hsvLayout.getChildAt(i);
                            appItemNumMap.put(view.getId(), pagName);
                        }

                        i++;
                    }
                    mHandler.sendEmptyMessage(REFRESH_DOWNLOAD);
                }
            }
        });
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String pkgName = null;
            Intent intent = null;
            boolean bInstalled = false;
            LogUtils.i("", "onClick 000:" + "; " + pkgName);
            try {
                int i = (Integer) view.getTag();

                ParserData.Root_Node action = ParserData.Layout_Node.parseJObject(jsonList.get(i), ParserData.Root_Node.class);
                String actionJson = action.action;

                ActionParser parser = new ActionParser();
                ActionParser.ParseIntent parseIntent = parser.parse(actionJson);
                if(parseIntent != null) {
                    pkgName = parseIntent.pkgName;
                    intent = parseIntent.i;
                }

                bInstalled = true;
                LogUtils.i("", "onClick 988:" + "; " + pkgName);
            } catch (PackageManager.NameNotFoundException e) {
                pkgName = e.getMessage();
                e.printStackTrace();
            }

            HashMap<Integer, String> sameNumMap = new HashMap<Integer, String>();
            List<View> viewList = appItemViewMap.get(pkgName);
            if (pkgName != null) {
                if (networkStatusOK(mcontext) == false) {
                    //网络异常提示
                    TipToast.getInstance().showToast(mcontext.getString(R.string.connect_Internet));
                } else if (viewList != null) {
                    sameNumMap.put(view.getId(), pkgName);
                    view.setClickable(false);

                    if (!createCircleProgressView(sameNumMap, "topic", false)) {
                        view.setClickable(true);
                    }
                }

            }

            if (intent != null) {
                if (intent.getFlags() == ActionParser.INTENT_VIDEO_FLAG) {

                    if(!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                    {
                        return;
                    }

                    String name = intent.getStringExtra("name");
                    String url = intent.getStringExtra("url");
                    LogUtils.i("play", "testPlayeVideo  name:" + name);
                    try {
                        XServiceManager.getLiteCCConnectorService().startPlayer(name, url, false);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                else if(intent.getIntExtra("type", -1) == ActionParser.INTENT_WEB_FLAG)
                {

                    if(!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                    {
                        return;
                    }

                    int androidVersion = android.os.Build.VERSION.SDK_INT;
                    if (androidVersion > 21) {
                        final String url = intent.getStringExtra("url");
                        CoocaaApplication.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    XServiceManager.getLiteCCConnectorService().startWebPoints(url);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    mcontext.startActivity(intent);
                    return;
                }

                try {
//                    mcontext.startActivity(intent);
                    HashMap<String,String> map = new HashMap<String,String>();
                    if(pkgName == null)
                        pkgName = "";
                    map.put("pkg", pkgName);
                    SkyStartActivity.startActivity(mcontext, mcontext.getClass().getName(), intent, map, false);
                    if(pkgName != null){
                        XServiceManager.getLiteCCConnectorService().startAppBonusPoints(pkgName);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (pkgName != null) {
                    if(!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                    {
                        return;
                    }
                    Uri uri = Uri.parse("skyview://com.coocaa.x/app/detail");
                    Intent i = new Intent();
                    i.setData(uri);
                    i.putExtra("id", pkgName);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
//                        mcontext.getApplicationContext().startActivity(i);
                        HashMap<String,String> map = new HashMap<String,String>();
                        SkyStartActivity.startActivity(mcontext, mcontext.getClass().getName(), i, map, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    };

    @Override
    public void onRemoved(final CircleProgressView view) {
        //
        LogUtils.i("", "onRemoved " + updateViewMap.size());
        if (updateViewMap.containsKey(view)) {
            AsyncTask.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseView baseView = (BaseView) updateViewMap.get(view);
                    int count = baseView.getChildCount();
                    LogUtils.i("", "baseView id = " + baseView.getId());
                    baseView.removeViewAt(count - 1);
                    baseView.setClickable(true);
                    updateViewMap.remove(view);
                    viewIdSet.remove(baseView.getId());
                }

            });
        }
    }

    public void removeDownload() {
        for (Object view : updateViewMap.keySet()) {
            BaseView baseView = (BaseView) updateViewMap.get(view);
            int count = baseView.getChildCount();
            baseView.removeViewAt(count - 1);
            baseView.setClickable(true);
            updateViewMap.remove(view);
            viewIdSet.remove(baseView.getId());
        }
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (!b)
            return;
        int left = hsv.getScrollX();
        int locId = left / (shotsWidth + spacing);
        if (locId == 0) {
            leftArrow.setVisibility(View.INVISIBLE);
        } else {
            leftArrow.setVisibility(View.VISIBLE);
        }
        if (countSize - locId == preCount) {
            rightArrow.setVisibility(View.INVISIBLE);
        } else {
            rightArrow.setVisibility(View.VISIBLE);
        }
        LogUtils.i("onFocusChange", "onFocusChange id = " + view.getTag() + ";" + slide.getVisibility() + ";" + left + ";" + locId);
    }

    OnKeyListener monKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if(isOneKeySetup && keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                oneKeySetupBtn.requestFocus();
                keyUpItemIndex = view.getId();
                return true;
            }
            return false;
        }
    };

    private boolean isAppInstalled(String packageName) {
        PackageManager pm = mcontext.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            //捕捉到异常,说明未安装
            installed = false;
        }
        return installed;
    }

    private boolean createCircleProgressView(final Map<Integer, String> itemMap, final String tag, final boolean bInit) {
        if (itemMap == null || itemMap.size() == 0 || tag == null) {
            return false;
        }

        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                String pkgName;
                int itemId;
                boolean bInstalled;
                for (Map.Entry<Integer, String> entry : itemMap.entrySet()) {
                    pkgName = entry.getValue();
                    itemId = entry.getKey();
                    bInstalled = isAppInstalled(pkgName);

                    CircleProgressView circleProgressView = CircleProgressViewFactory
                            .create(mcontext, pkgName, tag + itemId, bInstalled, bInit);

                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("pkgName", pkgName);
                    if (circleProgressView == null) {
                        LogUtils.i(tag, "circleProgressViewList == null" + ", bInit = " + bInit);
                        if (!bInit) {
                            msg.what = REFRESH_ITEM_CLICKABLE;
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                        }
                    } else {
                        bundle.putString("pkgName", pkgName);
                        msg.setData(bundle);
                        msg.obj = circleProgressView;
                        msg.what = REFRESH_DOWNLOAD_PROGRESS;
                        mHandler.sendMessage(msg);
                    }
                }
            }
        });

        return true;
    }

    private void checkCircleProgressView(HashMap<Integer, String> appItemNumMap) {
        Map<Integer, String> itemMap = appItemNumMap;

        if (itemMap != null && itemMap.size() > 0) {
            createCircleProgressView(itemMap, "topic", true);
        }
    }

    private void getAppInfoList() {
        if(jsonList == null)
            return;

        for(String json: jsonList) {
            ParserData.AppInfo_Node infoAction = ParserData.AppInfo_Node.parseJObject(json, ParserData.AppInfo_Node     .class);
            if(infoAction != null) {
                ParserData.AppInfo_Node.App_Info info = ParserData.AppInfo_Node.parseJObject(infoAction.appInfo, ParserData.AppInfo_Node.App_Info.class);
                if(info != null) {
                    TopicAppInfo appInfo = new TopicAppInfo();
                    appInfo.id = info.id;
                    appInfo.packagename = info.packagename;
                    appInfo.version = info.version;
                    appInfo.lmg =info.lmg;
                    appInfo.name =info.name;
                    appInfoList.add(appInfo);
                }
            }
        }
    }

}
